package com.sanploy.server.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.sanploy.server.YiquResp;
import com.sanploy.server.okhttp.OKhttpUtil;
import com.sun.javafx.binding.StringFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2017/6/19.
 */
@Component
public class WechatUtil {
    @Autowired
    private  WechatAsyncTask asyncTask;

    private  String appid = "wxd6c116eb2cd9ddf2";  //三策
    private   String secret = "6ac9da9a8a8dcfe770648d20e04a3ab5";
    private   WechatToken wechatToken;
    private    Gson gson = new Gson();
//    关注微信公众号链接
    private  String  connecturl = "https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzA3MDY5NTUxNw==#wechat_redirect";
//用户是否关注微信公众号    https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
//
//    private static String appid = "wxe8e00b4d23f4dbff";  //稞宏
//        private static  String secret = "90af456bcd8716b0aa04e629767346bd";


    public  WechatToken getAccessToken() throws IOException {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&" +
                "appid="+appid+"&secret="+secret;
        String json = OKhttpUtil.sendGet(requestUrl);
        System.out.println(json);
        if (json.contains("errcode")){
            return null;
        }
        wechatToken = gson.fromJson(json, WechatToken.class);
        return wechatToken;
    }

    public  WeixinOauth2Token getUserOpenid(String code) throws IOException {
        WeixinOauth2Token weixinOauth2Token;
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret +
                "&code=" + code + "&grant_type=authorization_code";
        String json = OKhttpUtil.sendGet(requestUrl);
        System.out.println(json);
        JSONObject jsonObject = JSON.parseObject(json);
        System.out.println(jsonObject.getString("access_token"));
        weixinOauth2Token = gson.fromJson(json,WeixinOauth2Token.class);

        return weixinOauth2Token;
    }

    public  WeixinUserInfo getWeixingUserInfo(String accessToken , String openid) throws IOException {
        WeixinUserInfo weixinUserInfo;
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openid;

        String json = OKhttpUtil.sendGet(requestUrl);
        System.out.println(json);
        weixinUserInfo = gson.fromJson(json,WeixinUserInfo.class);
        return weixinUserInfo;
    }

    /**
     * 引导用户关注微信并推送给设备
     * @param openid
     * @param name
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    public  String AttentionWechat(String openid, String name) throws IOException, InterruptedException {
        ConnectUserInfo connectUserInfo;
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+wechatToken.getAccess_token()+"&openid="+openid+"&lang=zh_CN";


        String json = OKhttpUtil.sendGet(requestUrl);
        System.out.println(json);
        connectUserInfo = gson.fromJson(json,ConnectUserInfo.class);
        int flag = 0;
        String returnUrl = "/focus.html";
        if (connectUserInfo.getSubscribe() == 1){
            returnUrl = "/bug-successful.html";
            flag = 11;
        }
        asyncTask.monitorAttention(requestUrl,name,flag,connectUserInfo); //推送给客户端设备
        return returnUrl;
    }

    public YiquResp outBug() throws IOException {
        String token = "fed"+System.currentTimeMillis();
        String json = OKhttpUtil.sendGet("http://app.eacheart.com:9090/type=8017?os=webapp&token=" + token + "&terminalno=" + "FED160620000012" + "&count=1");
        return gson.fromJson(json,YiquResp.class);
    }

    public  JsApi getSignPackage(String pathname) throws IOException {
        String jsapi_ticket = getJsapi_ticket(wechatToken.getAccess_token());
        return sign(jsapi_ticket, pathname);
    }

    public  String getJsapi_ticket(String accessToken) throws IOException {
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
        String json = OKhttpUtil.sendGet(url);
        System.out.println(json);
        JsapiTicket jsapiTicket = gson.fromJson(json,JsapiTicket.class);

        return jsapiTicket.getTicket();
    }



    public  JsApi sign(String jsapi_ticket, String url) {
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        JsApi jsApi = new JsApi();
        jsApi.setAppid(appid);
        jsApi.setNonceStr(nonce_str);
        jsApi.setSignature(signature);
        jsApi.setTimestamp(timestamp);


        return jsApi;
    }

    private  String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private  String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private  String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
